import mongoose from 'mongoose';
import moment from 'moment';
import { User } from './user';

const MemberSchema = new mongoose.Schema(
  {
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    name: String, // 会员名称
    expired: Number, // 失效时间
    source: String // 来源参数
  },
  { versionKey: false }
);
MemberSchema.index({ user: 1 }, { sparse: true, unique: true });

/**
 * 设置用户会员
 * @param {String} parmas.userid 用户ID
 * @param {String} parmas.memberName 会员名称
 */
MemberSchema.statics.setMember = async function (parmas) {
  const { userid, memberName, days = 0, source = 'default' } = parmas;
  if (!userid || !memberName) throw new Error('setMember参数错误');
  let expired = moment();
  switch (memberName) {
    case '年付会员':
      expired.add(1, 'year');
      break;
    case '半年付会员':
      expired.add(0.5, 'year');
      break;
    case '季付会员':
      expired.add(3, 'month');
      break;
    case '月付会员':
      expired.add(1, 'month');
      break;
    case '3天体验会员':
      expired.add(3, 'day');
      break;
    case '7天体验会员':
      expired.add(7, 'day');
      break;
    case '自定义天数会员':
      expired.add(days, 'day');
      break;
    default:
      break;
  }
  const user = await User.findById(userid);
  if (!user) throw new Error('setMember用户不存在');
  const member = await this.findOne({ user: userid });
  if (member) {
    // 更新会员记录
    const update = await this.updateOne({ _id: member._id }, { $set: { name: memberName, expired: expired.format('x'), source: source || member.source } });
    return update.ok;
  } else {
    // 新建会员记录
    const newMember = await this.create({
      user: mongoose.Types.ObjectId(userid),
      name: memberName,
      expired: expired.format('x'),
      source
    });
    const updateUser = await User.updateOne({ _id: userid }, { $set: { member: newMember._id } });
    return !!newMember && updateUser.ok;
  }
};

/**
 * 删除会员
 * @param {String} userid 用户ID
 */
MemberSchema.statics.deleteMember = async function (userid) {
  if (!userid) throw new Error('setMember参数错误');
  const deleteResult = await this.deleteOne({ user: userid });
  return !!deleteResult.ok;
};

const Member = mongoose.model('Member', MemberSchema);

export { Member };
